﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class main_uc_tender_app : DAO.ESWebUserControl
{
    private bool edit_app = false;
    private long appid = 0;
    string referrer_addr = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        InitializeUI();
        LoadPackingTypes(this.LangId);
        LoadSpecialConditionTypes(this.LangId);
        LoadGoodsTypes(this.LangId);
        LoadPlacementTypes(this.LangId);
       
        if (Request.QueryString["id"]!=null)
        {
            Int64.TryParse(Request.QueryString["id"].ToString(), out appid);
            LoadVehicleTypes(this.LangId);
            LoadTecnicalInfo(appid);
            //Edit Application
            if (Request.Cookies["texchange"] != null && Request.Cookies["texchange"]["logged"] != null && DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["logged"]) == "true")
            {
                if (Request.Cookies["texchange"]["cid"] != null /*&& DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["cid"].ToString()) == dr["company_id"].ToString()*/)
                {
                    if (Request.UrlReferrer != null)
                    {
                        referrer_addr = Request.UrlReferrer.ToString();
                        if (referrer_addr != null && referrer_addr != "")
                        {
                            if (referrer_addr.ToLower().IndexOf("myapplications.aspx") != -1)
                            {
                                ShowHideFields();
                            }
                        }
                    }
                }
            }
            //If user is admin
            if (Request.Cookies["texchange"]["type"] != null && DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["type"].ToString()) == "admin")
            {
                ShowHideFields();
            }
        }
    }

    private void ShowHideFields()
    {
        //Form Elements
        edit_app = true;
        ddlPackingTypes.Visible = true;
        ddlGoods.Visible = true;
        ddlSpecualConditionTypes.Visible = true;
        btn_UpdateTechicalInfo45.Visible = true;
        tbOtherInformattions.Visible = true;
        tbPaymentType.Visible = true;
        tbWeightOfGoods.Visible = true;
        tb_ClosingDate.Visible = true;
        tb_OppeningDate.Visible = true;
        ddlTransportTypes.Visible = true;
        ddlPlacementTypes.Visible = true;
        //Labels
        lblGoods.Visible = false;
        lblOtherInfo.Visible = false;
        lblPackingType.Visible = false;
        lblPaymentType.Visible = false;
        lblSpecCondition.Visible = false;
        lblWeightOfGoods.Visible = false;
        lblOppeningDate.Visible = false;
        lblClosingDate.Visible = false;
        lblPlacementType.Visible = false;
        lblTransportTypes.Visible = false;
    }

    private void LoadVehicleTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,10000,'id','desc') WHERE isActive = 'true'", conn))
            {
                long transport_type_id = getTransportTypebyAppId(appid);
                long type_id = 0;

                switch (transport_type_id)
                {
                    case 167://Air
                        lbl_type_of_transport.Text = DAO.TextBaseFactory.loadText("craft_type", this.LangId);
                        type_id = 1;
                    break;
                    case 165://Sea
                        lbl_type_of_transport.Text = DAO.TextBaseFactory.loadText("vessel_type", this.LangId);
                        type_id = 3;
                    break;
                    case 164://Road
                        lbl_type_of_transport.Text = DAO.TextBaseFactory.loadText("vehicle_type", this.LangId);
                        type_id = 14;
                    break;
                    case 166://Rail
                        lbl_type_of_transport.Text = DAO.TextBaseFactory.loadText("vehicle_type", this.LangId);
                        type_id = 13;
                    break;
                    default:
                        lbl_type_of_transport.Text = DAO.TextBaseFactory.loadText("vehicle_type", this.LangId);
                    break;

                }
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", type_id);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddlTransportTypes.Items.Clear();
                ddlTransportTypes.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlTransportTypes.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    private long getTransportTypebyAppId(long app_id)
    {
        long type_transport_id = 0;
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("select type_transport_id from Fn_ApplicationById(" + app_id + ")", conn))
            {
                object result = cmd.ExecuteScalar();
                if (result != null)
                {
                    Int64.TryParse(result.ToString(), out type_transport_id);
                }
            }
        }
        return type_transport_id;
    }

    private void LoadPlacementTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,10000,'id','desc') WHERE isActive = 'true'", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 8);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddlPlacementTypes.Items.Clear();
                ddlPlacementTypes.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlPlacementTypes.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    protected override void InitializeUI()
    {
        long langId = DAO.Connection.DEFAULT_LANGUAGE;
        if (Session["language"] != null)
            long.TryParse(Session["language"].ToString(), out langId);

        this.LangId = Convert.ToInt32(langId);
    }

    public void LoadTecnicalInfo(long appid)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SP_GetTechnicalInfo", conn))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.Add("@app_id", DbType.Int64).Value = appid;
                cmd.Parameters.Add("@type_offer_id", DbType.Int64).Value = 71;
                SqlDataReader dr = cmd.ExecuteReader();
                tb_application_id.Value = appid.ToString();

                while (dr.Read())
                {
                    tb_Tender_app_id.Value = dr["id"].ToString();
                    long type_goods_id;
                    lblGoods.Text = "N/A";
                    if (long.TryParse(dr["type_goods_id"].ToString(), out type_goods_id))
                    {
                        lblGoods.Text = LoadUniversalType(type_goods_id);
                        if (ddlGoods.Items.FindByValue(dr["type_goods_id"].ToString()) != null)
                        {
                            ddlGoods.Items.FindByValue(dr["type_goods_id"].ToString()).Selected = true;
                        }
                    }
                    //Opening_Date
                    DateTime date_var;
                    lblOppeningDate.Text = "N/A";
                    if (DateTime.TryParse(dr["opening_date"].ToString(), out date_var))
                    {
                        tb_OppeningDate.Text = date_var.ToShortDateString();
                        lblOppeningDate.Text = date_var.ToShortDateString(); 
                    }
                    //Cloasing_Date
                    lblClosingDate.Text = "N/A";
                    if (DateTime.TryParse(dr["closing_date"].ToString(), out date_var))
                    {
                        tb_ClosingDate.Text = date_var.ToShortDateString();
                        lblClosingDate.Text = date_var.ToShortDateString();
                    }
                    long transport_type_id;
                    lblTransportTypes.Text = "N/A";
                    if (long.TryParse(dr["transport_type_id"].ToString(), out transport_type_id))
                    {
                        lblTransportTypes.Text = LoadUniversalType(transport_type_id);
                        if (ddlTransportTypes.Items.FindByValue(dr["transport_type_id"].ToString()) != null)
                        {
                            ddlTransportTypes.Items.FindByValue(dr["transport_type_id"].ToString()).Selected = true;
                        }
                    }
                    long packing_type_id;
                    lblPackingType.Text = "N/A";
                    if (long.TryParse(dr["packing_type_id"].ToString(), out packing_type_id))
                    {
                        lblPackingType.Text = LoadUniversalType(packing_type_id);
                        if (ddlPackingTypes.Items.FindByValue(dr["packing_type_id"].ToString()) != null)
                        {
                            ddlPackingTypes.Items.FindByValue(dr["packing_type_id"].ToString()).Selected = true;
                        }
                    }
                    long placement_type_id;
                    lblPlacementType.Text = "N/A";
                    if (long.TryParse(dr["placement_type_id"].ToString(), out placement_type_id))
                    {
                        lblPlacementType.Text = LoadUniversalType(placement_type_id);
                        if (ddlPlacementTypes.Items.FindByValue(dr["placement_type_id"].ToString()) != null)
                        {
                            ddlPlacementTypes.Items.FindByValue(dr["placement_type_id"].ToString()).Selected = true;
                        }
                    }
                    long special_conditions_id;
                    lblSpecCondition.Text = "N/A";
                    if (long.TryParse(dr["special_condition_type"].ToString(), out special_conditions_id))
                    {
                        lblSpecCondition.Text = LoadUniversalType(special_conditions_id);
                        if (ddlSpecualConditionTypes.Items.FindByValue(dr["special_condition_type"].ToString()) != null)
                        {
                            ddlSpecualConditionTypes.Items.FindByValue(dr["special_condition_type"].ToString()).Selected = true;
                        }
                    }

                    lblPaymentType.Text = dr["payment_type_id"].ToString() != "" ? dr["payment_type_id"].ToString() : "N/A";
                    tbPaymentType.Text = lblPaymentType.Text; 

                    lblOtherInfo.Text = dr["other_information"].ToString() != "" ? dr["other_information"].ToString() : "N/A";
                    tbOtherInformattions.Text = lblOtherInfo.Text;

                    lblWeightOfGoods.Text = dr["weight_goods"].ToString() != "" ? dr["weight_goods"].ToString() : "N/A";
                    tbWeightOfGoods.Text = lblWeightOfGoods.Text;
                }
            }
        }
    }

    #region LoadUniversalType
    private string LoadUniversalType(long id)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            string cmd1 = "";
            Int64 langId = DAO.Connection.DEFAULT_LANGUAGE;
            if (Session["language"] != null)
            {
                Int64.TryParse(Session["language"].ToString(), out langId);
            }
            if (langId != DAO.Connection.DEFAULT_LANGUAGE)
                cmd1 = "SELECT id, name FROM dbo.Fn_GetUniversalTypeByLang(@id,@language_id)";
            else
                cmd1 = "SELECT id, name FROM dbo.Fn_GetUniversalTypeById(@id,@language_id)";
            using (SqlCommand cmd = new SqlCommand(cmd1, conn))
            {
                cmd.Parameters.Add("id", id);
                cmd.Parameters.Add("language_id", langId);

                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    return dr["name"].ToString();
                }
                dr.Close();
                return "";
            }
        }
    }
    #endregion

    #region btn_UpdateTechicalInfo_Click
    protected void btn_UpdateTechicalInfo45_Click(object sender, EventArgs e)
    {

    }
    #endregion
   
    private void LoadPackingTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,10000,'id','desc') WHERE isActive = 'true'", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 6);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddlPackingTypes.Items.Clear();
                ddlPackingTypes.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlPackingTypes.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    private void LoadGoodsTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,10000,'id','desc') WHERE isActive = 'true'", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 10);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddlGoods.Items.Clear();
                ddlGoods.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlGoods.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    private void LoadSpecialConditionTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,10000,'id','desc') WHERE isActive = 'true'", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 5);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddlSpecualConditionTypes.Items.Clear();
                ddlSpecualConditionTypes.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlSpecualConditionTypes.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    protected void btn_UpdateTechicalInfo45_Click1(object sender, EventArgs e)
    {
        SqlParameter[] pars = new SqlParameter[7];
        pars[0] = new SqlParameter("application_id", appid);
        pars[0].DbType = System.Data.DbType.Int64;
        pars[1] = new SqlParameter("packing_type_id", ddlPackingTypes.SelectedValue);
        pars[1].DbType = System.Data.DbType.Int64;
        pars[2] = new SqlParameter("type_goods_id", ddlGoods.SelectedValue);
        pars[2].DbType = System.Data.DbType.Int64;
        pars[3] = new SqlParameter("weight_goods", tbWeightOfGoods.Text);
        pars[3].DbType = System.Data.DbType.String;
        pars[4] = new SqlParameter("payment_type_id", tbPaymentType.Text);
        pars[4].DbType = System.Data.DbType.String;
        pars[5] = new SqlParameter("special_condition_type", ddlSpecualConditionTypes.SelectedValue);
        pars[5].DbType = System.Data.DbType.Int64;
        pars[6] = new SqlParameter("other_information", tbOtherInformattions.Text);
        pars[6].DbType = System.Data.DbType.String;
        pars[7] = new SqlParameter("id", tb_Tender_app_id.Value);
        pars[7].DbType = System.Data.DbType.Int64;

        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SP_UpdateStep3Tender", conn))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                foreach (SqlParameter p in pars)
                {
                    if (p != null && p.Value != null)
                    {
                        if (p.Value.ToString() != "0")
                            cmd.Parameters.Add(p);
                    }
                }
                cmd.ExecuteScalar().ToString();
            }
        }
        if (Request.Cookies["texchange"] != null &&
            Request.Cookies["texchange"]["logged"] != null && DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["logged"]) == "true" &&
            Request.Cookies["texchange"]["type"] != null && DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["type"].ToString()) == "admin")
        {
            Response.Redirect("~/Application.aspx");
        }
        else
        {
            Response.Redirect("~/MyApplications.aspx");
        }
    }
}
